{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#中值滤波：获取一定区域内(3*3)的像素，然后进行排序。选取中间值替换掉原来中心像素的值\n",
    "import cv2\n",
    "import numpy as np\n",
    "img = cv2.imread('image11.jpg',1)\n",
    "imgInfo = img.shape\n",
    "height = imgInfo[0]\n",
    "width = imgInfo[1]\n",
    "grayImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n",
    "dstImg = np.zeros((height,width,3),np.uint8)\n",
    "collect = np.zeros(9,np.uint8)\n",
    "for i in range(1,height-2):\n",
    "    for j in range(1,width-2):\n",
    "        k = 0\n",
    "        for m in range(-1,2):\n",
    "            for n in range(-1,2):   \n",
    "                gray = grayImg[i+m,j+n]\n",
    "                collect[k] = gray\n",
    "                k= k + 1\n",
    "        # 排序\n",
    "        for k in range(0,9):\n",
    "            for t in range(k+1,9):\n",
    "                if collect[k]<collect[t]:\n",
    "                    temp = collect[t]\n",
    "                    collect[t] = collect[k]\n",
    "                    collect[k] = temp\n",
    "        # 将中间值赋予像素\n",
    "        dstImg[i,j] = collect[4]\n",
    "cv2.imshow('dstImg',dstImg)\n",
    "cv2.imshow('grayImg',grayImg)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
